<template>
  <view class="register-container">
    <view class="header">
      <text class="title">用户注册</text>
    </view>
    <view class="input-group">
      <input 
        type="text" 
        v-model="username" 
        placeholder="请输入用户名(2-10位)"
        maxlength="10"
        @input="validateUsername"
      />
      <view class="error-message" v-if="usernameError">{{ usernameError }}</view>
    </view>
    <view class="input-group">
      <input 
        type="number" 
        v-model="phone" 
        placeholder="请输入手机号"
        maxlength="11"
        @input="validatePhone"
      />
      <view class="error-message" v-if="phoneError">{{ phoneError }}</view>
    </view>
    <view class="input-group">
      <input 
        type="password" 
        v-model="password" 
        placeholder="请输入密码(6-20位)"
        password
        @input="validatePassword"
      />
      <view class="error-message" v-if="passwordError">{{ passwordError }}</view>
    </view>
    <view class="input-group">
      <input 
        type="password" 
        v-model="confirmPassword" 
        placeholder="请再次输入密码"
        password
        @input="validateConfirmPassword"
      />
      <view class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</view>
    </view>
    <button 
      class="register-button" 
      @click="handleRegister"
      :disabled="isLoading"
    >
      {{ isLoading ? '注册中...' : '注册' }}
    </button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      phone: '',
      password: '',
      confirmPassword: '',
      usernameError: '',
      phoneError: '',
      passwordError: '',
      confirmPasswordError: '',
      isLoading: false,
      mockData: {
        users: []
      }
    };
  },
  created() {
    // 从本地存储加载已有用户数据
    const savedUsers = uni.getStorageSync('users');
    if (savedUsers) {
      this.mockData.users = savedUsers;
    } else {
      // 初始化默认用户数据
      this.mockData.users = [
        {
          "id": "1",
          "phone": "18812345678",
          "password": "gao123456",
          "username": "xiaolan"
        },
        // 其他默认用户...
      ];
    }
  },
  methods: {
    validateUsername() {
      if (!this.username) {
        this.usernameError = '请输入用户名';
        return false;
      }
      if (this.username.length < 2 || this.username.length > 10) {
        this.usernameError = '用户名长度应为2-10位';
        return false;
      }
      this.usernameError = '';
      return true;
    },
    validatePhone() {
      if (!this.phone) {
        this.phoneError = '请输入手机号';
        return false;
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        this.phoneError = '请输入正确的手机号';
        return false;
      }
      this.phoneError = '';
      return true;
    },
    validatePassword() {
      if (!this.password) {
        this.passwordError = '请输入密码';
        return false;
      }
      if (this.password.length < 6 || this.password.length > 20) {
        this.passwordError = '密码长度应为6-20位';
        return false;
      }
      this.passwordError = '';
      return true;
    },
    validateConfirmPassword() {
      if (!this.confirmPassword) {
        this.confirmPasswordError = '请再次输入密码';
        return false;
      }
      if (this.confirmPassword !== this.password) {
        this.confirmPasswordError = '两次输入的密码不一致';
        return false;
      }
      this.confirmPasswordError = '';
      return true;
    },
    async handleRegister() {
      if (!this.validateUsername() || !this.validatePhone() || 
          !this.validatePassword() || !this.validateConfirmPassword()) {
        return;
      }
      
      this.isLoading = true;
      
      try {
        // 检查用户名是否已存在
        const isUsernameExist = this.mockData.users.some(
          user => user.username === this.username
        );
        
        if (isUsernameExist) {
          throw new Error('用户名已存在');
        }
        
        // 检查手机号是否已注册
        const isRegistered = this.mockData.users.some(
          user => user.phone === this.phone
        );
        
        if (isRegistered) {
          throw new Error('该手机号已注册');
        }
        
        // 生成新用户ID
        const newUserId = String(Math.max(...this.mockData.users.map(u => parseInt(u.id))) + 1);
        
        // 创建新用户
        const newUser = {
          id: newUserId,
          phone: this.phone,
          password: this.password,
          username: this.username
        };
        
        // 添加到用户列表
        this.mockData.users.push(newUser);
        
        // 保存到本地存储
        uni.setStorageSync('users', this.mockData.users);
        
        uni.showToast({
          title: '注册成功',
          icon: 'success'
        });
        
        // 自动登录
        uni.setStorageSync('token', `token-${Date.now()}`);
        uni.setStorageSync('userInfo', {
          userId: newUser.id,
          username: newUser.username,
          phone: newUser.phone
        });
        
        setTimeout(() => {
          uni.navigateTo({ url: '/pages/login/login' });
        }, 1500);
        
      } catch (error) {
        uni.showToast({
          title: error.message || '注册失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.register-container {
  padding: 40rpx;
  height: 100vh;
  background-color: #f8f8f8;
}

.header {
  margin-bottom: 80rpx;
  text-align: center;
}

.title {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-group input {
  width: 100%;
  height: 100rpx;
  padding: 0 30rpx;
  border: 1px solid #e6e6e6;
  border-radius: 10rpx;
  font-size: 32rpx;
  background-color: #fff;
}

.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 10rpx;
  height: 30rpx;
}

.register-button {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  background-color: #007AFF;
  color: #fff;
  border: none;
  border-radius: 10rpx;
  font-size: 36rpx;
  margin-top: 40rpx;
}

.register-button[disabled] {
  background-color: #a0cfff;
}
</style>